package com.qian.service.ddj.serviceImpl;

import com.qian.api.ddj.model.Message;
import com.qian.api.ddj.service.IMessageService;
import com.qian.service.ddj.dao.MessageRepository;
import com.qian.service.ddj.entity.DdjMessage;
import com.yaowk.service.common.BaseRepository;
import com.yaowk.service.common.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.transaction.Transactional;

@Service
public class MessageServiceImpl extends BaseServiceImpl<Message, DdjMessage, Integer> implements IMessageService {
    @Autowired
    private MessageRepository dao;


    @Override
    @Transactional
    public Message save(Message message) {
        if (message.isNew()) {
            message = simpleSave(message);
        } else {
            DdjMessage ddjMessage = dao.findOne(message.getId());
            if (isNotEmpty(message.getContent())) {
                ddjMessage.setContent(message.getContent());
            }
            if (isNotEmpty(message.getTitle())) {
                ddjMessage.setTitle(message.getTitle());
            }
            if (isNotEmpty(message.getDate())) {
                ddjMessage.setDate(message.getDate());
            }
            message = entity2model(dao.save(ddjMessage));
        }
        return message;
    }

    @Override
    protected BaseRepository<DdjMessage, Integer> getDao() {
        return dao;
    }

    @Override
    protected DdjMessage model2Entity(Message model) {
        DdjMessage sysMessage = null;
        if (!ObjectUtils.isEmpty(model)) {
            sysMessage = new DdjMessage();
            sysMessage.setTitle(model.getTitle());
            sysMessage.setId(model.getId());
            sysMessage.setContent(model.getContent());
            sysMessage.setDate(model.getDate());
        }

        return sysMessage;
    }

    @Override
    protected Message entity2model(DdjMessage entity) {
        Message message = null;
        if (!ObjectUtils.isEmpty(entity)) {
            message = new Message();
            message.setTitle(entity.getTitle());
            message.setId(entity.getId());
            message.setContent(entity.getContent());
            message.setDate(entity.getDate());
        }
        return message;
    }
}
